//
//  ExaminationViewController.m
//  AssistantDriving
//
//  Created by dcr on 2017/8/30.
//  Copyright © 2017年 邓兆太. All rights reserved.
//

#import "ExaminationViewController.h"
#import "AnswerScrollView.h"
#import "SelectModelView.h"
#import "SheetView.h"
#import "AnswerModel.h"
#import "QuestionCollectManager.h"
#import "ImageButton.h"

@interface ExaminationViewController ()<SheetViewDelegate>
{
    AnswerScrollView *_answerScrollview;
    SelectModelView *_modelView;
    SheetView *_sheetView;
    int _count;
    NSTimer *_timer;
    UILabel *_timeLabel;
}
@end


@implementation ExaminationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self createData];
    [self.view addSubview:_answerScrollview];
    [self createToolBar];
    [self createSheetView];
}

- (void)createData{
    switch (_model) {
        case emulatePractice:
        {
            //全真模拟考试
            NSMutableArray *temArr = [[NSMutableArray alloc] init];
            NSArray *array = [DataManager getData:answer];
            NSMutableArray *dataArray = [[NSMutableArray alloc] init];
            [temArr addObjectsFromArray:array];
            for(int i = 0; i < 100; i++){
                int index = arc4random()%(temArr.count);
                [dataArray addObject:temArr[index]];
                [temArr removeObjectAtIndex:index];
            }
            _count = (int)dataArray.count;
            _answerScrollview = [[AnswerScrollView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight-124) andDataArray:dataArray];
        }
            break;
        case preferredNotAnswer:
        {
            //优先未做题
            NSMutableArray *temArr = [[NSMutableArray alloc] init];
            NSArray *array = [DataManager getData:answer];
            NSMutableArray *dataArray = [[NSMutableArray alloc] init];
            NSArray *doneArr = [QuestionCollectManager getDoneQuestion];
            [temArr addObjectsFromArray:array];
            //删除已做过的题
            for(int i = 0; i < doneArr.count; i++){
                for(int j = 0; j < temArr.count; j++){
                    if([doneArr[i] isEqualToString:temArr[j]]){
                        [temArr removeObjectAtIndex:j];
                        break;
                    }
                }
            }
            //添加题目
            if(temArr.count > 100){
                for(int i = 0; i < 100; i++){
                    int index = arc4random()%(temArr.count);
                    [dataArray addObject:temArr[index]];
                    [temArr removeObjectAtIndex:index];
                }
            }else{
                NSMutableArray *temArr1 = [[NSMutableArray alloc] init];
                [temArr1 addObjectsFromArray:doneArr];
                for(int i = 0; i < temArr.count; i++){
                    [dataArray addObject:temArr[i]];
                }
                for(int j = 0; j < 100-temArr.count; j++){
                    int index = arc4random()%(temArr1.count);
                    [dataArray addObject:temArr[index]];
                    [temArr1 removeObjectAtIndex:index];
                }
            }
            _count = (int)dataArray.count;
            _answerScrollview = [[AnswerScrollView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight-124) andDataArray:dataArray];
        }
            break;
    }
    [self createNaviBtn];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(runTimer) userInfo:nil repeats:true];
    _timeLabel = [[UILabel alloc] init];
    _timeLabel.frame = CGRectMake(0, 0, 100, 64);
    _timeLabel.textAlignment = NSTextAlignmentCenter;
    _timeLabel.text = @"60:00";
    self.navigationItem.titleView = _timeLabel;
}

- (void)createNaviBtn{
    UIBarButtonItem *itemRigth = [[UIBarButtonItem alloc] init];
    itemRigth.title = @"交卷";
    [itemRigth setTarget: self];
    [itemRigth setAction:@selector(clickPaper)];
    self.navigationItem.rightBarButtonItem = itemRigth;
}

- (void)clickPaper{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定要交卷吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不，谢谢" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
        
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"是的，我要交卷" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        int score = 0;
        NSArray *myAnswerArr = _answerScrollview.hadAnswerArray;
        NSArray *answerArr = _answerScrollview.datas;
        for(int i = 0; i < myAnswerArr.count; i++){
#warning   题目类型的判断
            AnswerModel *model = answerArr[i];
            NSString *myAnswerStr = [NSString stringWithFormat:@"%c", 'A'-1+[myAnswerArr[i] intValue]];
            NSString *answerStr = model.manswer;
            if([myAnswerStr isEqualToString:answerStr]){
                score++;
            }
        }
        //保存处理
        NSLog(@"score = %d", score);
        [self.navigationController popViewControllerAnimated:true];
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    
    [self presentViewController:alert animated:true completion:nil];
}

- (void)runTimer{
    static int time = 3600;
    time--;
    _timeLabel.text = [NSString stringWithFormat:@"%d:%d", time/60, time%60];
}

//创建底部二个按钮
- (void)createToolBar{
    UIView *barView = [[UIView alloc] initWithFrame:CGRectMake(0, MainScreenHeight-60-64, MainScreenWidth, 60)];
    barView.backgroundColor = [UIColor whiteColor];
    NSString *count = [NSString stringWithFormat:@"%d", _count];
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    [arr addObjectsFromArray:@[count, @"收藏"]];
    
    for(int i = 0; i < arr.count; i++){
        ImageButton *btn = [ImageButton buttonWithType:UIButtonTypeSystem];
        btn.backgroundColor = [UIColor clearColor];
        
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d",16+i*2]] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d-2",16+i*2]] forState:UIControlStateHighlighted];
        btn.tag = 1000+i;
        [btn addTarget:self action:@selector(onClickButton:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        [btn setTitleColor:GeneralColor1 forState:UIControlStateNormal];
        [btn.titleLabel setFont:WeekFont4];
        [btn verticalImageAndTitle:15.0];
        [barView addSubview:btn];
        CGFloat x = (MainScreenWidth/4.0) + (MainScreenWidth/2.0)*i - 20;
        [btn mas_makeConstraints:^(MASConstraintMaker *make){
            make.left.mas_equalTo(x);
            make.topMargin.mas_equalTo(5);
            make.size.mas_equalTo(CGSizeMake(40, 40));
        }];
    }
    [self.view addSubview:barView];
}

- (void)onClickButton:(UIButton *)sender{
    switch (sender.tag) {
        case 1000:
        {
            [UIView animateWithDuration:0.3 animations:^{
                _sheetView.frame = CGRectMake(0, 80, self.view.frame.size.width, self.view.frame.size.height-80);
                _sheetView.backView.alpha = 0.8;
            }];
        }
            break;
            
        case 1001:
        {    //收藏本题
            AnswerModel *model = _answerScrollview.datas[_answerScrollview.currentPage];
            [QuestionCollectManager addCollectQuestion:[model.mid intValue]];
        }
            break;
            
        default:
            break;
    }
}

//创建答案的表视图控件
- (void)createSheetView{
    CGRect rect = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-80);
    _sheetView = [[SheetView alloc] initWithFrame:rect withSuperView:self.view andQuesCount:_count];
    [self.view addSubview:_sheetView];
    _sheetView.delegate = self;
}

- (void)backBtnClicked{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定要离开考试吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不，谢谢" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
        
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"是的，我要离开" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        [super backBtnClicked];
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:true completion:nil];
}

#pragma mark - delegate
-(void)SheetViewClick:(int)index{
    //点击题目的索引切换内容
    UIScrollView *scrollView = _answerScrollview->_scrollView;
    scrollView.contentOffset = CGPointMake((index)*scrollView.frame.size.width, 0);
    [scrollView.delegate scrollViewDidEndDecelerating:scrollView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
